package com.liuyk.activity;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.liuyk.compress.CompressListener;
import com.liuyk.compress.Compressor;
import com.liuyk.compress.InitListener;
import com.liuyk.main.activity.R;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 压缩
 * <p>
 * Created by Liuyk on 2017/8/29.
 */
public class CompressActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = "CompressActivity";

    private EditText mCompressInfo;
    private MediaPlayer mMediaPlayer;

    private Compressor mCompressor;
    private final String currentInputVideoPath = "";
    private final String currentOutputVideoPath = "";
    private final String cmd = "-y -i " + currentInputVideoPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
            "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s 640x480 -aspect 16:9 " + currentOutputVideoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compress);
        mCompressInfo = findViewById(R.id.compress_info);

        mMediaPlayer = new MediaPlayer();

        mCompressor = new Compressor(this);
        mCompressor.loadBinary(new InitListener() {
            @Override
            public void onLoadSuccess() {
                Log.v(TAG, "load library succeed");
            }

            @Override
            public void onLoadFail(String reason) {
                Log.i(TAG, "load library fail:" + reason);
            }
        });

        findViewById(R.id.compress).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        String inPath = getCompressInPath("test.mp4");
        File file = new File(inPath);
        if (file.exists()) {
            try {
                mMediaPlayer.setDataSource(inPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int videoW = getVideoThumbnail(inPath).getWidth();
            int videoH = getVideoThumbnail(inPath).getHeight();
            String cmd = "-y -i " + inPath + " -strict -2 -vcodec libx264 -preset ultrafast " +
                    "-crf 24 -acodec aac -ar 44100 -ac 2 -b:a 96k -s " + videoW + "x" + videoH + " -aspect 16:9 " +
                    getCompressOutPath("test.mp4");

            execCommand(cmd);
        } else {
//            Toast("文件不存在");
        }
    }

    private void execCommand(String cmd) {
        mCompressInfo.append(cmd + "\n");
        mCompressor.execCommand(cmd, new CompressListener() {
            @Override
            public void onExecSuccess(String message) {
                Log.i(TAG, "success " + message);
                String result = "inputPath: " + getCompressInPath("test.mp4") + "\n" +
                        "size: " + getFileSize(getCompressInPath("test.mp4")) + "\n" +
                        "out: " + getCompressOutPath("test.mp4") + "\n" +
                        "size: " + getFileSize(getCompressOutPath("test.mp4"));
                mCompressInfo.append("onExecSuccess\n" + result + "\n");
            }

            @Override
            public void onExecFail(String reason) {
                Log.i(TAG, "fail " + reason);
                mCompressInfo.append("fail " + reason + "\n");
            }

            @Override
            public void onExecProgress(String message) {
                Log.i(TAG, "onExecProgress： " + message);
                String progress = getProgress(message).trim();
                if (!TextUtils.isEmpty(progress)) {
                    Log.v(TAG, "当前压缩进度：" + progress);
                    mCompressInfo.append(progress + "\n");
                }
            }
        });
    }

    private String getFileSize(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return "0 MB";
        } else {
            long size = f.length();
            return (size / 1024f) / 1024f + "MB";
        }
    }

    private String getProgress(String source) {
        //progress frame=   28 fps=0.0 q=24.0 size= 107kB time=00:00:00.91 bitrate= 956.4kbits/s
        Pattern p = Pattern.compile("00:\\d{2}:\\d{2}");
        Matcher m = p.matcher(source);
        if (m.find()) {
            //00:00:00
            String result = m.group(0);
            String[] temp = result.split(":");
            Double seconds = Double.parseDouble(temp[1]) * 60 + Double.parseDouble(temp[2]);
            Log.v(TAG, "current second = " + seconds);
            int i = mMediaPlayer.getDuration() / 1000;
            if (0 != i) {
                return seconds / i + "";
            }
            return "0";
        }
        return "";
    }

    private String getCompressOutPath(String name) {
        final File file = new File(Environment.getExternalStorageDirectory(), "Compress/OutCompress");
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(file.getAbsolutePath(), name).getAbsolutePath();
    }

    private String getCompressInPath(String name) {
        final File file = new File(Environment.getExternalStorageDirectory(), "Compress/InCompress");
        if (!file.exists()) {
            file.mkdirs();
        }
        return new File(file.getAbsolutePath(), name).getAbsolutePath();
    }

    //视频第一帧缩略图
    public static Bitmap getVideoThumbnail(String videoPath) {
        final MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(videoPath);
        return media.getFrameAtTime();
    }
}
